const express = require('express');
const http = require('http');
const bodyParser =  require('body-parser') 
const cookieParser = require('cookie-parser');
const session =  require('express-session');
const logger = require('morgan');
const mongoose = require('mongoose');
const main =  require('./server');
const socketIO =  require('./server/socketIO/socketIO_server');

var env = process.env.NODE_ENV || 'development'
var port = process.env.PORT || '5000';
var dbUrl = 'mongodb://127.0.0.1:27017/bosszp';
if(env === 'development'){
  dbUrl = 'mongodb://127.0.0.1:27017/bosszp';
}

mongoose.Promise = global.Promise;  
mongoose.connect(dbUrl, {useNewUrlParser:true},function(){
  console.log("数据库连接成功")
})


const app = express();
const cors = require('cors');
app.use(cors({credentials: true}));
app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(cookieParser('express_react_cookie'));
app.use(session({
    secret: 'express_react_cookie',
    resave: false,
    saveUninitialized: true,
    cookie: {maxAge: 60 * 1000 * 120}//过期时间
}));
app.use(bodyParser.json()); //application/json
app.use(bodyParser.urlencoded({extended: true})); //application/x-www-form-urlencoded
app.set('port', port);
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});
app.use('/', main);//展示页面路由

// 启动服务，监听4000端口
const server = http.createServer(app);
socketIO(server);
server.listen(port);


